﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LongSCADA_WPF.Helpers;
using LongSCADA_WPF.Models;
using Masuit.Tools;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace LongSCADA_WPF.ViewModels
{
    public partial class FormulaViewModel:ObservableObject
    {
        private readonly GlobalHelper _globalHelper;


        //侧边目录固定格式
        [ObservableProperty]
        ObservableCollection<FormulaEntity> _formulaList = new();
        
        [ObservableProperty]
        FormulaEntity ?_selectedFormula;
        
        [ObservableProperty]
        FormulaEntity ?_currentFormula;

        [ObservableProperty]
        string _searchText;

        public FormulaViewModel(GlobalHelper globalHelper)
        {
            _globalHelper = globalHelper;

        }

        [RelayCommand]
        void SelectFormula(FormulaEntity formula)
        {
            //更新选中状态，将配方列表中未选中的配方全部置为未选中
            FormulaList.ForEach(x => x.IsSelected = false);

            //2.选中当前配方，formula 设为选中状态
            formula.IsSelected = true;

            //3.将选中的配方信息传递给 SelectedFormula
            SelectedFormula = formula;
            //4.将当前配方信息传递给 CurrentFormula
            CurrentFormula = formula.DeepClone();
        }
        [RelayCommand]
        void Load()
        {
            FormulaList.Clear();
            SqlSugarHelper.Db.Queryable<FormulaEntity>()
                .OrderBy(x=>x.CreateTime,SqlSugar.OrderByType.Desc)
                .ToList()
                .ForEach(x => FormulaList.Add(x));   
        }

        [RelayCommand]
        void QueryFormula()
        {
            FormulaList.Clear();
            SqlSugarHelper.Db.Queryable<FormulaEntity>()
                .Where(x => x.Name.Contains(SearchText))
                .OrderBy(x => x.CreateTime, SqlSugar.OrderByType.Desc)
                .ToList()
                .ForEach(x => FormulaList.Add(x));
            if (FormulaList.Count ==1)
            {
                FormulaList[0].IsSelected = true;
                SelectedFormula = FormulaList[0];
                CurrentFormula = FormulaList[0].DeepClone();
            }
        }
        [RelayCommand]
        void NewFormula()
        {
            //更新选中状态，将配方列表中未选中的配方全部置为未选中
            FormulaList.ForEach(x => x.IsSelected = false);
            SelectedFormula = null;
            CurrentFormula = new FormulaEntity();
        }
        [RelayCommand]
        void SaveFormula()
        {
            try
            {
                //1.验证必须含有字段
                if (string.IsNullOrEmpty(CurrentFormula.Name))
                {
                    MessageBox.Show("配方名称不能为空！");
                    return;
                }
                //如果是现有配方
                if (SelectedFormula != null)
                {
                    //2.更新现有配方
                    FormulaEntity? existFormula = FormulaList.FirstOrDefault(x => x.Id == SelectedFormula.Id);
                    if (!existFormula.IsNullOrEmpty())
                    {
                        CurrentFormula.UpdateTime = DateTime.Now;
                        int index = FormulaList.IndexOf(existFormula);
                        FormulaList[index] = CurrentFormula;
                    }
                }
                else
                {
                    //3.新增配方
                    CurrentFormula.CreateTime = DateTime.Now;
                    CurrentFormula.UpdateTime = DateTime.Now;
                    FormulaList.Add(CurrentFormula);
                }
                //4.将所有配方 FormulaList 保存到数据库 --- 插入 Or 更新，而不是所有数据
                //出现“Need primary key or WhereColumn” 1、检查是否右主键；2添加泛型<>
                int rows = SqlSugarHelper.Db.Storageable<FormulaEntity>(FormulaList)
                    .ExecuteCommand();
                if (rows > 0)
                {
                    MessageBox.Show("保存成功！");
                }
                else
                {
                    MessageBox.Show("保存失败！");
                }
            }
            catch (Exception ex)
            {

                Debug.WriteLine(ex.Message);
            }
        }
        [RelayCommand]
        void DeleteFormula()
        {
            if (SelectedFormula == null)
            {
                MessageBox.Show("请先选择要删除的配方！");
                return;
            }
            if (MessageBox.Show("确定要删除该配方吗？", "提示", MessageBoxButton.YesNo)==MessageBoxResult.Yes)
            {
                FormulaList.Remove(SelectedFormula);
                int rows = SqlSugarHelper.Db.Deleteable(SelectedFormula)
                    .ExecuteCommand();
                if (rows > 0)
                {
                    MessageBox.Show("删除成功！");
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
        }
        [RelayCommand]
        void DownloadFormula()
        {
            try
            {
                foreach (var prop in typeof(FormulaEntity).GetProperties())
                {
                    string? address = _globalHelper.WriteEntityList
                        .FirstOrDefault(x => x.En == prop.Name)?.Address;
                    if (!address.IsNullOrEmpty())
                    {
                        //判断PLC是否连接，如果连接，则下载数据
                        if (_globalHelper.IsPLCConnected)
                        {
                            var value = prop.GetValue(CurrentFormula);
                            if (value != null)
                            {
                                _globalHelper.Plc.WriteAsync(address, (float)value);
                            }
                        }
                        else
                        {
                            MessageBox.Show("请先连接PLC！");
                            return;
                        }
                    }
                }
                MessageBox.Show("配方下载成功");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
                return;
            }
        }
    }
}
